package org.ciallo.simplemusicplayer.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.card.MaterialCardView;
import com.google.android.material.textfield.TextInputLayout;
import org.ciallo.simplemusicplayer.R;
import org.ciallo.simplemusicplayer.activity.FavoritesActivity;
import org.ciallo.simplemusicplayer.activity.MainActivity;
import org.ciallo.simplemusicplayer.activity.PlaylistSongsActivity;
import org.ciallo.simplemusicplayer.activity.RecentPlayActivity;
import org.ciallo.simplemusicplayer.adapter.PlaylistGridAdapter;
import org.ciallo.simplemusicplayer.data.model.PlaylistInfo;
import org.ciallo.simplemusicplayer.data.model.Song;
import org.ciallo.simplemusicplayer.util.Constants;
import org.ciallo.simplemusicplayer.viewmodel.FavoritesViewModel;
import org.ciallo.simplemusicplayer.viewmodel.PlaylistViewModel;
import org.ciallo.simplemusicplayer.viewmodel.SharedViewModel;
import timber.log.Timber;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * @author Jukomu
 * @Description: 首页Fragment，显示快捷入口和用户歌单
 * @Package: org.ciallo.simplemusicplayer.fragment
 * @Project: SimpleMusicPlayer
 * @name: HomeFragment
 * @Date: 2025/5/28-02:07
 * @Filename: HomeFragment
 */
public class HomeFragment extends Fragment {

    private TextView tvPlaylistSearchLabel;
    private MaterialCardView cardLocalMusic, cardRecentPlay, cardMyFavorites;
    private RecyclerView recyclerViewPlaylists;
    private TextView tvEmptyPlaylists;
    private Button btnCreatePlaylist; // 也可以是 MaterialButton
    private PlaylistGridAdapter playlistAdapter;
    private PlaylistViewModel playlistViewModel;
    private SharedViewModel sharedViewModel; // 如果需要与播放状态交互
    private FavoritesViewModel favoritesViewModel;

    public HomeFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 初始化ViewModel
        playlistViewModel = new ViewModelProvider(this).get(PlaylistViewModel.class);
        favoritesViewModel = new ViewModelProvider(requireActivity()).get(FavoritesViewModel.class);
        sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
        // 初始化UI控件
        cardLocalMusic = view.findViewById(R.id.card_home_local_music);
        cardRecentPlay = view.findViewById(R.id.card_home_recent_play);
        cardMyFavorites = view.findViewById(R.id.card_home_my_favorites);
        recyclerViewPlaylists = view.findViewById(R.id.recyclerView_home_playlists);
        tvEmptyPlaylists = view.findViewById(R.id.textView_home_empty_playlists);
        btnCreatePlaylist = view.findViewById(R.id.button_home_create_playlist);
        tvPlaylistSearchLabel = view.findViewById(R.id.textView_home_playlist_search_label);

        setupQuickEntries();
        setupPlaylistRecyclerView();
        observeViewModels();

        btnCreatePlaylist.setOnClickListener(v -> showCreatePlaylistDialog());
    }

    /**
     * 设置快捷入口的点击事件。
     */
    private void setupQuickEntries() {
        cardLocalMusic.setOnClickListener(v -> {
            if (getActivity() instanceof MainActivity) {
                BottomNavigationView bnv = getActivity().findViewById(R.id.bottom_navigation_view_main);
                if (bnv != null) {
                    bnv.setSelectedItemId(R.id.nav_local_music_main);
                }
            }
        });

        cardRecentPlay.setOnClickListener(v -> {
            // 跳转到最近播放页面 (需要创建 RecentPlayActivity)
            startActivity(new Intent(getActivity(), RecentPlayActivity.class));
        });

        cardMyFavorites.setOnClickListener(v -> {
            // 跳转到我的收藏页面 (需要创建 FavoritesActivity)
            startActivity(new Intent(getActivity(), FavoritesActivity.class));
        });
    }

    /**
     * 设置歌单列表的 RecyclerView。
     */
    private void setupPlaylistRecyclerView() { // Adapter 现在处理 PlaylistInfo
        playlistAdapter = new PlaylistGridAdapter(playlistInfo -> { // PlaylistInfoClickListener
            if (playlistInfo.id == Constants.FAVORITES_PLAYLIST_ID) {
                if (getActivity() != null) {
                    startActivity(new Intent(getActivity(), FavoritesActivity.class));
                }
            } else {
                if (getActivity() != null) {
                    Intent intent = new Intent(getActivity(), PlaylistSongsActivity.class);
                    intent.putExtra(PlaylistSongsActivity.EXTRA_PLAYLIST_ID, playlistInfo.id);
                    intent.putExtra(PlaylistSongsActivity.EXTRA_PLAYLIST_NAME, playlistInfo.name);
                    intent.putExtra(PlaylistSongsActivity.EXTRA_PLAYLIST_COVER_URI, playlistInfo.displayCoverArtUri);
                    startActivity(intent);
                }
            }
        });
        // 确认这里的 LayoutManager 是你想要的 (例如 GridLayoutManager(getContext(), 2) 或 LinearLayoutManager)
        recyclerViewPlaylists.setLayoutManager(new LinearLayoutManager(getContext())); // XML中是LinearLayoutManager
        // 如果你想要网格，这里也应该是 GridLayoutManager
        // recyclerViewPlaylists.setLayoutManager(new GridLayoutManager(getContext(), 2));
        recyclerViewPlaylists.setAdapter(playlistAdapter);
    }


    /**
     * 观察 ViewModel 中的 LiveData 以更新UI。
     */
    private void observeViewModels() {
        // 1. 观察 SharedViewModel 中的全局搜索查询词
        sharedViewModel.currentSearchQuery.observe(getViewLifecycleOwner(), query -> {
            Timber.d("HomeFragment: Observed global search query: '%s'", query);
            // 只有当 HomeFragment 是当前可见Fragment时，才更新 PlaylistViewModel 的查询
            // (或者如果希望首页搜索总是全局同步，则不需要此检查)
            // 简单起见，我们总是更新 PlaylistViewModel
            playlistViewModel.updateSearchQuery(query);

            // 更新搜索结果提示的可见性和文本
            if (query != null && !query.trim().isEmpty()) {
                tvPlaylistSearchLabel.setText(String.format(Locale.getDefault(), "“%s”的歌单搜索结果：", query.trim()));
                tvPlaylistSearchLabel.setVisibility(View.VISIBLE);
            } else {
                tvPlaylistSearchLabel.setVisibility(View.GONE);
            }
        });

        // 2. 观察 PlaylistViewModel 中过滤后的用户创建的歌单列表
        playlistViewModel.userPlaylistsToDisplay.observe(getViewLifecycleOwner(), userPlaylists -> {
            Timber.d("HomeFragment: User playlists to display updated, count: %d", userPlaylists != null ? userPlaylists.size() : 0);
            // 现在 userPlaylistsToDisplay 只包含用户创建的歌单（可能已根据搜索过滤）
            // 我们还需要 "我的收藏"
            // currentNormalPlaylists = userPlaylists != null ? new ArrayList<>(userPlaylists) : new ArrayList<>();
            // tryUpdateCombinedList(); // 调用旧的合并方法，但现在只处理 userPlaylists
            // 这部分逻辑需要重写，以结合 userPlaylists 和 favoritesViewModel.favoriteSongs
            updateCombinedListWithSearch(userPlaylists, favoritesViewModel.favoriteSongs.getValue(), sharedViewModel.currentSearchQuery.getValue());

        });

        // 3. 观察收藏歌曲列表 (用于构造“我的收藏”项)
        favoritesViewModel.favoriteSongs.observe(getViewLifecycleOwner(), favoriteSongs -> {
            Timber.d("HomeFragment: Favorite songs updated, count: %d", favoriteSongs != null ? favoriteSongs.size() : 0);
            // 当收藏夹变化时，也需要重新构建合并列表
            // List<PlaylistInfo> currentUserPlaylists = playlistViewModel.userPlaylistsToDisplay.getValue();
            // updateCombinedListWithSearch(currentUserPlaylists, favoriteSongs, sharedViewModel.currentSearchQuery.getValue());
            // 为了避免在两个 observer 中都调用 updateCombinedListWithSearch，
            // 可以使用 MediatorLiveData，或者在两个 observer 中都调用一个统一的更新方法，
            // 并确保这个方法能处理其中一个数据源为null的情况（在初始加载时）。
            // 当前的设计，每个 observer 更新自己的数据，然后调用一个统一的 combineAndDisplay 方法。
            updateCombinedListWithSearch(
                    playlistViewModel.userPlaylistsToDisplay.getValue(), // 获取当前用户歌单
                    favoriteSongs,                                       // 最新的收藏歌曲
                    sharedViewModel.currentSearchQuery.getValue()        // 当前的搜索查询
            );
        });

        playlistViewModel.createdPlaylistId.observe(getViewLifecycleOwner(), newPlaylistId -> {
            if (newPlaylistId != null && newPlaylistId > 0) {
                Toast.makeText(getContext(), "歌单创建成功!", Toast.LENGTH_SHORT).show();
                // 可选：滚动到新创建的歌单或跳转到其详情页
            } else if (newPlaylistId != null && newPlaylistId == -1L) { // 检查错误标志
                // 错误信息已由errorMessage LiveData处理
            }
        });

        playlistViewModel.isLoading.observe(getViewLifecycleOwner(), isLoading -> {
            // TODO: 根据 isLoading 状态显示/隐藏加载指示器 (例如在创建歌单时)
        });

        playlistViewModel.errorMessage.observe(getViewLifecycleOwner(), error -> {
            if (error != null && !error.isEmpty()) {
                Toast.makeText(getContext(), error, Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 合并“我的收藏”和用户创建的歌单（可能已根据搜索过滤），并更新UI。
     *
     * @param userCreatedPlaylists 用户创建的歌单列表 (PlaylistInfo)，已根据搜索过滤。
     * @param favoriteSongs        收藏的歌曲列表 (Song)，用于计算收藏夹数量。
     * @param currentSearchQuery   当前的搜索查询词，用于显示正确的空状态消息。
     */
    private void updateCombinedListWithSearch(@Nullable List<PlaylistInfo> userCreatedPlaylists,
                                              @Nullable List<Song> favoriteSongs,
                                              @Nullable String currentSearchQuery) {

        if (userCreatedPlaylists == null || favoriteSongs == null) {
            // 如果任一数据源尚未加载完成，则不进行合并更新，等待两者都准备好
            Timber.d("updateCombinedListWithSearch: Waiting for all data sources. UserPlaylists: %s, FavSongs: %s",
                    userCreatedPlaylists == null ? "null" : "loaded",
                    favoriteSongs == null ? "null" : "loaded");
            return;
        }

        List<PlaylistInfo> combinedList = new ArrayList<>();
        boolean searchActive = currentSearchQuery != null && !currentSearchQuery.trim().isEmpty();

        // 1. 创建并添加“我的收藏”特殊歌单项
        // “我的收藏”项不参与搜索过滤，总是显示（除非设计要求在搜索时也隐藏它）
        int favoriteCount = favoriteSongs.size();
        String favoritesCoverUri = "android.resource://" + requireActivity().getPackageName() + "/" + R.drawable.ic_favorite_playlist_placeholder;
        PlaylistInfo favoritesPlaylistInfo = new PlaylistInfo(
                Constants.FAVORITES_PLAYLIST_ID,
                getString(R.string.my_favorites_playlist_name),
                favoriteCount,
                favoritesCoverUri,
                PlaylistInfo.TYPE_FAVORITES_PLAYLIST
        );
        // 只有在非搜索状态，或者搜索状态但“我的收藏”也符合某种搜索逻辑时才添加
        // 目前的设计是首页搜索只针对用户创建的歌单名，所以“我的收藏”可以一直显示，或者在搜索时隐藏。
        // 为了简单，我们先让它一直显示在列表顶部，除非搜索结果不包含它（这不符合当前搜索歌单名的逻辑）
        // 折中：如果正在搜索，并且搜索词不匹配“我的收藏”，则不显示它。
        // 但更简单的做法是：“我的收藏”总是显示，搜索只过滤下面的用户歌单。
        // 这里我们选择：如果搜索激活，不特别处理“我的收藏”，让它自然地不被歌单名搜索匹配到。
        // **修正：首页歌单列表应该总是包含“我的收藏”作为第一项，搜索只过滤用户创建的歌单。**
        if (!searchActive) { // 只有在没有激活搜索时，才将 "我的收藏" 和用户歌单合并显示
            // 或者，如果希望“我的收藏”一直显示，然后下面是搜索结果，可以调整
            combinedList.add(favoritesPlaylistInfo);
            combinedList.addAll(userCreatedPlaylists);
        } else {
            // 如果正在搜索，列表只包含搜索到的用户歌单
            combinedList.addAll(userCreatedPlaylists);
        }


        // 更新Adapter
        if (playlistAdapter != null) {
            playlistAdapter.submitList(combinedList);
        }

        // 更新空状态和搜索结果标签
        if (searchActive) {
            // tvPlaylistSearchLabel 已在 sharedViewModel.currentSearchQuery 的观察者中设置
            if (combinedList.isEmpty()) {
                tvEmptyPlaylists.setText(String.format(Locale.getDefault(), "没有找到与“%s”相关的歌单", currentSearchQuery.trim()));
                tvEmptyPlaylists.setVisibility(View.VISIBLE);
                recyclerViewPlaylists.setVisibility(View.GONE);
            } else {
                tvEmptyPlaylists.setVisibility(View.GONE);
                recyclerViewPlaylists.setVisibility(View.VISIBLE);
            }
        } else { // 非搜索状态
            // tvPlaylistSearchLabel 已在 sharedViewModel.currentSearchQuery 观察者中隐藏
            if (combinedList.isEmpty()) { // 此时 combinedList 应该只可能包含“我的收藏”且其为空
                tvEmptyPlaylists.setText(R.string.empty_playlists_message_home_combined);
                tvEmptyPlaylists.setVisibility(View.VISIBLE);
                recyclerViewPlaylists.setVisibility(View.GONE); // 或者 recyclerView 显示空的“我的收藏”
            } else if (combinedList.size() == 1 && combinedList.get(0).id == Constants.FAVORITES_PLAYLIST_ID && combinedList.get(0).songCount == 0) {
                // 只有“我的收藏”且为空
                tvEmptyPlaylists.setText(R.string.empty_playlists_message_home_combined);
                tvEmptyPlaylists.setVisibility(View.VISIBLE);
                recyclerViewPlaylists.setVisibility(View.VISIBLE); // 显示空的“我的收藏”
            }
            else {
                tvEmptyPlaylists.setVisibility(View.GONE);
                recyclerViewPlaylists.setVisibility(View.VISIBLE);
            }
        }
    }


    /**
     * 显示创建新歌单的对话框。
     */
    private void showCreatePlaylistDialog() {
        if (getContext() == null) return;
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        LayoutInflater inflater = LayoutInflater.from(requireContext());
        View dialogView = inflater.inflate(R.layout.dialog_create_edit_playlist, null);
        builder.setView(dialogView);

        final TextInputLayout tilPlaylistName = dialogView.findViewById(R.id.textInputLayout_playlist_name_dialog);
        final EditText etPlaylistName = dialogView.findViewById(R.id.editText_playlist_name_dialog);
        final TextInputLayout tilPlaylistDesc = dialogView.findViewById(R.id.textInputLayout_playlist_desc_dialog);
        final EditText etPlaylistDesc = dialogView.findViewById(R.id.editText_playlist_desc_dialog);

        builder.setTitle(R.string.playlist_dialog_title_create); // "新建歌单"

        builder.setPositiveButton(R.string.playlist_create_button_text, (dialog, which) -> { // "创建"
            String name = etPlaylistName.getText().toString().trim();
            String description = etPlaylistDesc.getText().toString().trim();

            if (name.isEmpty()) {
                if (tilPlaylistName != null) tilPlaylistName.setError("歌单名称不能为空");
                Toast.makeText(getContext(), "歌单名称不能为空", Toast.LENGTH_SHORT).show();
                // 此处对话框会自动关闭，若想阻止，需要更复杂处理
                return;
            }
            if (tilPlaylistName != null) tilPlaylistName.setError(null);

            playlistViewModel.createPlaylist(name, description);
        });
        builder.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.cancel());
        builder.show();
    }
}